﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using VAdvantage.Grids;
using VAdvantage.Classes;
using VAdvantage.Logging;
using System.Windows.Data;

namespace VAdvantage.Controls
{
    public partial class VFile : UserControl,IControl
    {

        public enum DialogType
        {
            OpenFile = 0,
            SaveFile = 1,
            Custom = 2
        };
        public enum SelectionType
        {
            FilesOnly = 0,
            DirectoryOnly = 1,
        };

        #region "Declaration"

        private String _columnName;
        /** Selection Mode					*/
        private SelectionType _selectionMode = SelectionType.DirectoryOnly;
        /** Save/Open						*/
        private DialogType _dialogType = DialogType.Custom; //JFileChooser.CUSTOM_DIALOG;
        /**	Logger			*/
        private static VLogger log = VLogger.GetVLogger(typeof(VFile).FullName);

        private bool _mandatory = false;

        private int _displayType = DisplayType.FileName;

        private GridField _field;

        private bool _readOnly;

        private bool _focus = false;

        Binding binding = null;


        OpenFileDialog openFileDialog = null;
        SaveFileDialog saveFileDialog = null;

        private TextBox txtFile;
        private Button btnFile;



        #endregion


        public static readonly DependencyProperty ValueChangedProperty =
     DependencyProperty.Register("Value", typeof(String), typeof(VAdvantage.Controls.VFile), new PropertyMetadata((o, e) =>
     {
         ((VFile)o).SetValue((Object)e.NewValue);

     }));


        public Object Value
        {
            get
            {
                return ((Object)GetValue(VFile.ValueChangedProperty));
            }
            set
            {
                SetValue(VFile.ValueChangedProperty, value);
            }
        }

        public VFile()
        {
            InitializeComponent();

            foreach (UIElement ele in LayoutRoot.Children)
            {
                if (ele is TextBox)
                {
                    txtFile = (TextBox)ele;
                }
                else if (ele is Button)
                {
                    btnFile = (Button)ele;
                }
            }
        }

        public VFile(String columnName, bool mandatory,
        bool isReadOnly, bool isUpdateable, bool files):this()
        {
           
            //this.Name = columnName;
            _columnName = columnName;
            if (files)	//	default Directories
                _selectionMode = SelectionType.FilesOnly;
            String col = columnName.ToLower();
            if (col.IndexOf("open") != -1 || col.IndexOf("load") != -1)
                _dialogType = DialogType.OpenFile;
            else if (col.IndexOf("save") != -1)
                _dialogType = DialogType.SaveFile;


            //Editable
            if (isReadOnly || !isUpdateable)
                SetReadOnly(true);
            else
                SetReadOnly(false);

            if (!DataBase.GlobalVariable.IsVisualEditor)
            {
                this.btnFile.Click +=new RoutedEventHandler(btnFile_Click);
                this.txtFile.TextChanged += new TextChangedEventHandler(txtFile_TextChanged);
                this.txtFile.KeyDown += new KeyEventHandler(txtFile_KeyDown);
                this.txtFile.KeyUp += new KeyEventHandler(txtFile_KeyUp);

                openFileDialog = new OpenFileDialog();
                saveFileDialog = new SaveFileDialog();


            }
            else
            {
                //this.txtFile.MouseDown += new MouseEventHandler(txtFile_MouseDown);
                //this.txtFile.MouseMove += new MouseEventHandler(txtFile_MouseMove);
                //this.txtFile.MouseUp += new MouseEventHandler(txtFile_MouseUp);
                //this.txtFile.MouseEnter += new EventHandler(VFile_MouseEnter);
            }
            SetIsMandatory(mandatory);
        }

        string txtVal = "";
        bool isChanged = false;
        void txtFile_KeyUp(object sender, KeyEventArgs e)
        {
            isChanged = !txtFile.Text.Equals(txtVal);
        }

        void txtFile_KeyDown(object sender, KeyEventArgs e)
        {
            txtVal = txtFile.Text;
            if (e.Key == Key.Enter || e.Key == Key.Tab)
            {
                if (VetoableChangeListener != null && isChanged)
                {
                   _focus = true;
                   VetoableChangeListener(this, EventArgs.Empty);
                    _focus = false;
                }
            }
            isChanged = false;

        }

        void txtFile_TextChanged(object sender, TextChangedEventArgs e)
        {
            SetColor();
        }

        private void btnFile_Click(object sender, RoutedEventArgs e)
        {
            String _value = this.txtFile.Text;
            bool? dialogResult = null;

            if (_selectionMode == SelectionType.DirectoryOnly)
            {
                dialogResult = openFileDialog.ShowDialog();
                if (dialogResult != null && (bool)dialogResult)
                {
                    this.txtFile.Text = openFileDialog.File.Name;
                    // SetGridText();
                }
            }

            else
            {
                if (_dialogType == DialogType.SaveFile)
                {
                    saveFileDialog.DefaultExt = "*.txt";

                    dialogResult = saveFileDialog.ShowDialog();
                    if (dialogResult != null && (bool)dialogResult)
                    {
                        this.txtFile.Text = saveFileDialog.SafeFileName;
                        //SetGridText();
                    }
                }

                else
                {
                    //openFileDialog.Title = _columnName;

                    openFileDialog.Filter = "All files (*.*)|*.*";
                     dialogResult = openFileDialog.ShowDialog();
                    
                    if (dialogResult != null && (bool)dialogResult)
                    {
                        System.IO.FileInfo fi = openFileDialog.File;

                        
                        this.txtFile.Text = fi.Name;
                       // SetGridText();
                    }
                }
            }
            txtFile.Focus();
            if (!Utility.Util.IsEqual(_value, this.txtFile.Text))
            {
                if (VetoableChangeListener != null)
                {
                    _focus = true;
                    VetoableChangeListener(this, EventArgs.Empty);
                    _focus = false;
                }
            }
        }

        #region IControl

        public event EventHandler VetoableChangeListener;

        public int GetDisplayType()
        {
            return _displayType;
        }

        public void SetDisplayType(int displayType)
        {
            _displayType = displayType;
        }

        public bool GetIsReadonly()
        {
            return _readOnly;
        }

        public void SetReadOnly(bool readOnly)
        {
            _readOnly = readOnly;

            this.txtFile.IsReadOnly = readOnly;

            if (readOnly)
            {
                btnFile.Visibility = System.Windows.Visibility.Collapsed;
            }
            else
            {
                btnFile.Visibility = System.Windows.Visibility.Visible;
            }
            SetBackGround(readOnly);
        }

        private SolidColorBrush backColorBrush = new SolidColorBrush();

       

        public void SetBackGround(bool value)
        {
            if (value)
            {
                backColorBrush.Color = DataBase.GlobalVariable.READONLY_TEXT_BACK_COLOR;
                this.txtFile.Background = backColorBrush;
            }
            else
            {
                backColorBrush.Color = DataBase.GlobalVariable.NORMAL_TEXT_BACK_COLOR;
                this.txtFile.Background = backColorBrush;
                SetColor();
            }
        }

        private void SetColor()
        {
            if (_mandatory)
            {
                if (this.txtFile.Text == "")
                {
                    backColorBrush.Color = DataBase.GlobalVariable.MANDATORY_TEXT_BACK_COLOR;
                    this.txtFile.Background = backColorBrush;
                }
                else
                {
                    backColorBrush.Color = DataBase.GlobalVariable.NORMAL_TEXT_BACK_COLOR;
                    this.txtFile.Background = backColorBrush;
                    if (_field != null)
                        _field.SetError(false);
                }
            }
        }

        public GridField GetField()
        {
            return _field;
        }

        public void SetField(GridField mField)
        {
            _field = mField;
        }

        public string GetName()
        {
           return this._columnName;
        }

        public void SetName(string name)
        {
            this._columnName = name;
        }

        public string GetText()
        {
            return txtFile.Text;
        }

        public object GetValue()
        {
            return txtFile.Text;
        }

        public void SetValue(object value)
        {
            txtFile.Text = value == null ? "" : value.ToString();
        }

        public bool GetIsMandatory()
        {
            return _mandatory;
        }

        public void SetIsMandatory(bool value)
        {
            _mandatory = value;
        }

       

        public string GetSelectedText()
        {
            return txtFile.Text;
        }

        public bool IsDisabled()
        {
            return !this.IsEnabled;
        }

        public void SetDisabled(bool disabled)
        {
            this.IsEnabled = !disabled;
        }

        public int GetTabIndex()
        {
            return this.TabIndex;
        }

        public void SetTabindex(int tabindex)
        {
            this.TabIndex = tabindex;
        }

        public bool Multiline
        {
            get
            {
                return false;
            }
            set
            {
                throw new NotImplementedException();
            }
        }

        public bool Visible
        {
            get
            {
                return this.Visibility == System.Windows.Visibility.Visible;
            }
            set
            {
                this.Visibility = value ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed;
            }
        }

        public bool Focused
        {
            get { return _focus;}
        }

        public string BindValue
        {
            set
            {
                binding = new Binding(value);
                binding.Mode = BindingMode.OneWay;
                this.SetBinding(VFile.ValueChangedProperty, binding);
            }
        }

        public void Dispose()
        {
            binding = null;
            openFileDialog = null;
            saveFileDialog = null;
            
        }

#endregion
    }
}
